<template>
	<view class="test-detail"> 
		<scroll-view scroll-y class="scroll-sel" v-if="!visibleStudyWord" :class="selCls">
			<view class="flex flex-col">
				<view class="word">
					<text v-if="visibleTitle">{{getTitle()}}</text>
					<text v-else-if="visiblePlayBtn"
						style="font-size: var(--text-12);margin-top: 10rpx;color: #777;">听音频选中文</text>
					<u-icon name="volume" class="play" v-if="visiblePlayBtn" color="#5f5d5d" size="40"
						@click="playMp3(current.MP3)"></u-icon>
				</view>
				<view style="text-align: center;">
					<text style="font-size: var(--text-12); color: #777;">{{getTitleHelp()}}</text>
				</view>
				<view class="option-selection">
					<view class="option text-18" :class="optionClass(item)" v-for="(item, index) in choices"
						:key="item.ID + '-' + index" @click="confirm(item)">
						<view class="sort">{{index+1}}</view>{{getText(item)}}
					</view>
					<view class="text-18 jump" style="display: flex;text-align: center; margin-top:20px;">
						<view class="text-16" style="flex:1; color: #777;padding:10px;">
							<text v-if="jump && choiceItem == null"  @click="handleJump" style="">跳过</text>
							<text v-if="showTimer && state.countdown>0 && choiceItem == null" style="padding-left:10px;">({{state.countdown}})</text>
						</view> 
					</view>
				</view>
				<view class="sentence-warp" v-if="visibleSentence">
					<!-- #ifdef H5 -->
					<view class="begin">提示：<u-icon name="volume" @click="palyAudio" color="#5f5d5d" size="18"></u-icon>
					</view>
					<!-- #endif -->
					<!-- #ifdef MP -->
					<view class="begin">提示：<u-icon name="volume" @click="palyAudio" color="#5f5d5d" size="28"></u-icon>
					</view>
					<!-- #endif -->
					<!-- <view class="sentenct" v-if="hasTemplate(TestTemplates.YYH, type)">{{current.SentenceSnapshot.SentenceEn}}</view> -->
					<sentence-linght-words v-if="hasTemplate([TestTemplates.YYH,TestTemplates.TX], type)"
						:words="current" :sentence="current.SentenceSnapshot" />
					<view class="sentenct-zh" v-else>{{current.SentenceSnapshot.SentenceCn}}</view>
				</view>
				<view class="h-50px w-full">

				</view>
			</view>
		</scroll-view>
		<view v-else>
			<StudyWord :current="current" />
		</view>

		<view class="btn-c bottom-btn-box">
			<u-button @click="visibleStudyWord=true" v-if="visibleViewWord" class="next-btn" type="warning"
				:plain="true">
				<view class="next-text">查看</view>
			</u-button>
			<view style="width: 20rpx;" v-if="visibleViewWord && visibleNext"></view>
			<u-button @click="gonext" v-if="visibleNext" class="next-btn" style="margin-right: 2px;" type="warning"
				:plain="true">
				<view class="next-text">继续</view>
			</u-button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, watch, computed, onUnmounted, nextTick, inject } from 'vue';
	import { useStudyStore, IWord, IUseSelectedTemplate, TestTemplates } from '@/store/study';
	import { createOptionsMixins, levenshteinDistance, lodash, randomArray, isEmpty, isEmptyObj } from '@/utils';
	import { getTemplateType, hasTemplate } from '@/common/hooks/test';
	import { useSoundEffect, useTimer } from '@/common/hooks';
	import SentenceLinghtWords from '../sentence-linght-words/sentence-linght-words.vue';
	import StudyWord from '../study-word/study-word.vue';


	/** 组件参数类型 */
	interface IProps {
		/** 做题模式 */
		type ?: { template : IUseSelectedTemplate };
		/** 当前测试词汇 */
		current ?: IWord,
		/** 是否开启答题确认模式 */
		pause ?: boolean;
		/** 是否开启氛围模式 */
		effect ?: boolean;
		/** 混淆词组 */
		data ?: IWord[];
		/** 是否开启跳过模式 */
		jump ?: boolean;
		/** 是否开启答题错误进入词汇学习模式 */
		errLearn ?: boolean;
		/** 计时器状态栏样式 */
		timerBarSty ?: string;
		/** 是否开启计时器 */
		showTimer ?: boolean;
	}

	/** 单词训练：单选 */
	defineOptions({
		name: 'single-selection',
		inheritAttrs: false,
		options: {
			virtualHost: true
		}
	});

	// 声明组件基本要素
	const props = withDefaults(defineProps<IProps>(), {
		data: () : IWord[] => [],
		pause: true,
		effect: false,
		jump: false,
		errLearn: false,
		timerBarSty: '',
		showTimer: false
	})
	const emit = defineEmits(['next']);

	// 师傅是伴读模式
	const isteacher = inject('isteacher');
	// 是否是复习课
	const isreview = inject('isreview');
	// 是否是二次验证
	const doubleVisible = inject('doubleVisible');

	// hooks 初始化
	const studyStore = useStudyStore();
	const { state, startDownTime, clearTimer } = useTimer();
	const { playMp3, palySuccessMp3, playFailMp3 } = useSoundEffect();

	// 声明用户变量
	// 选项列表
	const choices = ref<IWord[]>([]);
	// 是否答题正确
	const IsRight = ref(false);
	// 选中的选项
	const choiceItem = ref(null);
	// 题目文本显示状态
	const visibleTitle = ref(false);
	// 音频播放按钮显示状态
	const visiblePlayBtn = ref(false);
	// 学习界面显示状态
	const visibleStudyWord = ref(false);

	// 声明计算属性
	const selCls = computed(() => {
		if (!isteacher && !isreview) {
			const msClass = doubleVisible ? 'sel-double-visible' : 'sel-rember';
			// 正式课
			if (visibleViewWord.value || visibleNext.value) {
				return `${msClass} has-btn`;
			}
			return msClass;
		}

		// 保温课
		if (isteacher && isreview) {
			if (visibleViewWord.value || visibleNext.value) {
				return 'sel-teacher-review has-btn';
			}
			return 'sel-teacher-review';
		}

		// 自主复习
		if (isreview) {
			if (visibleViewWord.value || visibleNext.value) {
				return 'sel-review has-btn';
			}
			return 'sel-review';
		}

		return '';
	})
	// 句子显示状态
	const visibleSentence = computed(() => {
		return lodash.has(props.current, 'SentenceSnapshot.SentenceEn')
	})
	// 继续按钮显示状态
	const visibleNext = computed(() => {
		if (choiceItem.value === null) {
			return false;
		}
		return props.pause;
	})
	// 单词学习按钮显示状态
	const visibleViewWord = computed(() => {
		if (choiceItem.value === null) {
			return false;
		}
		return props.errLearn && !visibleStudyWord.value;
	})
	// 选项样式
	const optionClass = computed(() => {
		if (props.current == null) {
			return () => { };
		}
		return (item : IWord) => {
			//console.log('item', item)
			const classObj : any = {};
			if (choiceItem.value) {
				const isHintRightItem = props.current.WordId === item.WordId;
				const isHintErrorIten = choiceItem.value.WordId === item.WordId;
				if (isHintRightItem) {
					classObj.success = true;
				} else if (isHintErrorIten) {
					classObj.error = true;
				}
			}
			return classObj;
		}
	})

	// 跳过事件
	function handleJump() {
		uni.showModal({
			content: '是否确认跳过?'
		}).then(res => {
			if (res.confirm) {
				// 清理 timer
				clearTimer(true);
				nextTick().then(() => {
					// 执行下一步
					emit("next", choiceItem.value, false, true);
				})
			}
		})
	}

	function gonext() {
		clearTimer(true)
		if (choiceItem.value == null) {
			return;
		}
		emit("next", choiceItem.value, IsRight.value, false);
	}

	function confirm(item : IWord) {
		if (choiceItem.value != null) {
			return;
		}
		clearTimer();

		if (item.WordId == props.current.WordId) {
			IsRight.value = true;
			if (props.effect) {
				palySuccessMp3();
			}
		} else {
			IsRight.value = false;
			if (props.effect) {
				playFailMp3();
			}
		}
		choiceItem.value = item;
		if (!props.pause) {
			gonext();
		}
	}

	function getTitleHelp() {
		if (props.type == null) {
			return;
		}
		const { HYY, YYH, TX } = TestTemplates;
		switch (getTemplateType(props.type)) {
			case HYY.type:
				return "选出正确的英文";
			case YYH.type:
				return "选出正确的中文";
			case TX.type:
				return "听音选出正确的中文";
			default:
				return "未定义"
		}
	}

	function getTitle() {
		if (props.type == null) {
			return;
		}
		const { HYY, YYH, TX } = TestTemplates;
		switch (getTemplateType(props.type)) {
			case HYY.type:
				return props.current.Mean;
			case YYH.type:
				return props.current.Word;
			case TX.type:
				return props.current.MP3;
			default:
				return "未定义"
		}
	}

	function getText(item : IWord) {
		if (props.type == null) {
			return;
		}
		const { HYY, YYH, TX } = TestTemplates;
		switch (getTemplateType(props.type)) {
			case HYY.type:
				return item.Word;
			case YYH.type:
				return item.Mean;
			case TX.type:
				return item.Mean;
			default:
				return "未定义"
		}
	}


	function palyAudio() {
		if (props.current.SentenceSnapshot.Audio) {
			playMp3(props.current.SentenceSnapshot.Audio)
		}
	}

	watch(
		() => [props.current, props.type],
		(nVal : any[], oVal) => {
			clearTimer();
			if (isEmptyObj(nVal[0]) || isEmptyObj(nVal[1])) {
				return;
			}

			// 防止重复加载导致数据异常
			if (oVal) {
				if (JSON.stringify(nVal[0]) === JSON.stringify(oVal[0]) && getTemplateType(nVal[1]) === getTemplateType(oVal[1])) {
					return
				}
			}

			const { HYY, YYH, TX } = TestTemplates;
			if (!hasTemplate([HYY, YYH, TX], nVal[1])) return;

			// console.log('nVal', nVal)
			// console.log('oVal', oVal)
			choiceItem.value = null;
			visibleTitle.value = false;
			visiblePlayBtn.value = false;
			IsRight.value = false;
			visibleStudyWord.value = false;

			choices.value = [];
			choices.value.push(nVal[0]);

			const suffle = randomArray(nVal[0].testShuffle)

			for (var i = 0; i < suffle.length; i++) {
				if (nVal[0].Word == suffle[i]["Word"]) {
					continue;
				} else {
					if (choices.value.length < 4) {
						var disMean = levenshteinDistance(nVal[0].Mean, suffle[i]["Mean"]);
						var disWord = levenshteinDistance(nVal[0].Word, suffle[i]["Word"]);

						// console.log(disMean);
						// console.log(disWord);

						if (disMean < (nVal[0].Mean.length > suffle[i]["Mean"].length ? nVal[0].Mean.length / 3 : suffle[i]["Mean"].length / 3)
							|| disWord < (nVal[0].Word.length > suffle[i]["Word"].length ? nVal[0].Word.length / 3 : suffle[i]["Word"].length / 3)) {
							continue;
						}
						choices.value.push(suffle[i]);
					} else {
						break;
					}
				}
			}

			switch (getTemplateType(nVal[1])) {
				case HYY.type:
					visibleTitle.value = true;
					visiblePlayBtn.value = false;
					break;
				case YYH.type:
					visibleTitle.value = true;
					visiblePlayBtn.value = true;
					console.log('single-selection >>> YYH >>> playMp3', nVal[0].MP3)
					playMp3(nVal[0].MP3);
					break;
				case TX.type:
					visibleTitle.value = false;
					visiblePlayBtn.value = true;
					console.log('single-selection >>> TX >>> playMp3', nVal[0].MP3)
					playMp3(nVal[0].MP3);
					break;
			}
			randomArray(choices.value);
			// console.log('choices.value', choices.value)
			choices.value.push({
				Word: '不认识',
				Mean: '不认识',
				WordId: 0
			})

			// 若开启了计时器，开始倒计时
			if (props.showTimer) {
				startDownTime(10, () => {
					confirm({
						Word: '不认识',
						Mean: '不认识',
						WordId: 0
					});
				});
			}
		},
		{ immediate: true, deep: true },
	);

	onUnmounted(() => {
		console.log('onUnmounted >>> single-selection')
		clearTimer();
	})
</script>

<style lang="scss" scoped>
	.btn-c {
		display: flex;
		align-items: center;
	}
	 

	/* #ifdef H5 */
	.scroll-sel {
		height: calc(100vh - 190px);
	}

	.sel-rember {
		height: calc(100vh - 190px);
	}

	.sel-rember.has-btn {
		height: calc(100vh - 190px);
	}

	.sel-double-visible {
		height: calc(100vh - 157px);
	}

	.sel-double-visible.has-btn {
		height: calc(100vh - 207px);
	}

	.sel-teacher-review {
		height: calc(100vh - 140px);
	}

	.sel-teacher-review.has-btn {
		height: calc(100vh - 190px);
	}

	.sel-review {
		height: calc(100vh - 65px);
	}

	.sel-review.has-btn {
		height: calc(100vh - 117px);
	}

	/* #endif */

	/* #ifdef MP */
	.scroll-sel {
		height: calc(100vh - 378rpx);
	}

	.sel-rember {
		height: calc(100vh - 385rpx);
	}

	.sel-rember.has-btn {
		height: calc(100vh - 470rpx);
	}

	.sel-double-visible {
		height: calc(100vh - 385rpx);
	}

	.sel-double-visible.has-btn {
		height: calc(100vh - 425rpx);
	}

	.sel-teacher-review {
		height: calc(100vh - 170rpx);
	}

	.sel-teacher-review.has-btn {
		height: calc(100vh - 250rpx);
	}

	.sel-review {
		height: calc(100vh - 53rpx);
	}

	.sel-review.has-btn {
		height: calc(100vh - 136rpx);
	}

	/* #endif */

	.return-btn {
		position: absolute;
		left: 10px;
		top: 5px;
		z-index: 8;
	}

	.timer-btn {
		position: absolute;
		right: 10px;
		top: 5px;
		z-index: 8;
	}

	.play {
		margin-top: 16rpx;
		margin-left: 5px;
	}

	.word {
		display: flex;
		justify-content: center;
		align-items: center;
		color: var(--font-color);
		font-size: 50rpx;
		margin-top: 10rpx;
		min-height: 80rpx;
	}

	.sort {
		/* #ifdef H5 */
		width: 20px;
		height: 20px;
		line-height: 20px;
		/* #endif */

		/* #ifdef MP */
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		/* #endif */

		border-radius: 50%;
		background-color: #777;
		color: #fff;
		text-align: center;
		font-size: var(--text-12);
		margin-left: -34px;
		margin-right: 10px;
		margin-top: 3.5px;
	}

	.option-selection {
		.option {
			/* #ifdef H5 */
			min-height: 70px;
			margin-top: 15px;
			border-radius: 10px;
			padding-left: 50px;
			/* #endif */

			/* #ifdef MP */
			min-height: 124rpx;
			margin-top: 30rpx;
			border-radius: 20rpx;
			padding-left: 100rpx;
			/* #endif */

			border: 1px solid #b6b6b7;
			color: var(--font-color);
			display: flex;
			align-items: center;
		}

		.option.error {
			background-color: #c9caca;
		}

		.option.success {
			background-color: #92cb94;
			color: #fefefe;
		}

		.option:hover {
			//background-color: #c9caca;
		}
	}

	.sentence-warp {
		/* #ifdef H5 */
		padding: 9px;
		/* #endif */

		/* #ifdef MP */
		padding: 18rpx;
		margin-top: 30rpx;
		/* #endif */

		.begin {
			color: var(--font-color);
			font-size: var(--text-16);
		}

		.sentenct {
			color: var(--font-color);
			font-size: 24rpx;
			margin-top: 20rpx;
		}

		.sentenct-zh {
			color: #a1a1a1;
			font-size: 24rpx;
			margin-top: 8rpx;
			text-indent: 2em;
		}
	}

	.next-btn {
		flex: 1 !important;
	}

	.next-text {
		font-size: 38rpx;
		font-weight: bold;
		display: flex;
	}

	/* 针对 1280px 分辨率 */
	@media(min-width:1200px) {
		.option-selection {
			margin-top: 40rpx;

			.option {
				min-height: 140rpx;
				border-radius: 20rpx;
				padding-left: 100rpx;
				margin-bottom: 30rpx;
				font-size: 40rpx;
			}
		}


		.sentence-warp {
			padding: 18rpx;
			margin-top: 60rpx;

			.begin {
				font-size: 30rpx;
			}

			.sentenct {
				font-size: 30rpx;
				margin-top: 20rpx;
			}

			.sentenct-zh {
				font-size: 30rpx;
				margin-top: 8rpx;
			}
		}

	}
</style>